package com.ruyuan.engine.router;

import com.ruyuan.engine.pojo.ClientLog;
import com.ruyuan.engine.pojo.CombinationRuleParam;
import com.ruyuan.engine.pojo.RuleEventParam;
import com.ruyuan.engine.service.CombinationRuleServiceImpl;
import com.ruyuan.engine.utils.RuleCommonProcessUtils;
import org.apache.flink.api.common.state.ListState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class FLinkStateService {
    protected static final Logger log = LoggerFactory.getLogger(FLinkStateService.class);

    ListState<ClientLog> listState;

    public FLinkStateService(ListState<ClientLog> listState) {
        this.listState = listState;
    }

    /**
     * 根据组合条件和时间范围得到返回值：
     *      记录在组合条件中满足规则的下标
     *
     * */
    public String getCombinationCountByState(CombinationRuleParam combinationRuleParam,long startTime,long endTime) throws Exception {
        //获取状态
        Iterable<ClientLog> clientLogs = listState.get();
        //具体的规则
        List<RuleEventParam> ruleEventParams = combinationRuleParam.getRuleEventParams();
        //判断数据，输出结果
        StringBuilder stringBuilder = new StringBuilder();
        for(ClientLog clientLog:clientLogs) {
            long detailTime = Long.parseLong(clientLog.getDetailTime());
            //时间在规则匹配的时间区间
            if (detailTime >= startTime && detailTime<= endTime) {
                for(int i=1;i<= ruleEventParams.size();i++) {
                    //把满足的规则的下标放入stringBuilder
                    if (RuleCommonProcessUtils.eventMatchRuleParam(clientLog,ruleEventParams.get(i-1))) {
                        stringBuilder.append(i);
                        break;
                    }

                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 根据组合条件和查询的时间范围：查询该组合出现的次数
     * */
    public int combinationMatchCount(CombinationRuleParam combinationRuleParam,long startTime,long endTime) throws Exception {
        String combinationCountByState = getCombinationCountByState(combinationRuleParam, startTime, endTime);
        //解析次数
        return RuleCommonProcessUtils.sequenceMathCountByRegex(combinationCountByState, combinationRuleParam.getRegexp());
    }
}
